package com.xuyiwei.mayi.service;

import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import com.xuyiwei.mayi.base.BaseApiService;
import com.xuyiwei.mayi.base.ResponseBase;
import com.xuyiwei.mayi.constants.Constants;
import com.xuyiwei.mayi.entity.UserEntity;
import com.xuyiwei.mayi.mapper.UserDao;
import com.xuyiwei.mayi.mq.RegisterEmailProducter;
import com.xuyiwei.mayi.utils.MD5Util;
import com.xuyiwei.mayi.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by xuyiwei on 2019/4/26.
 */
@RestController
@Slf4j
public class MemberServiceImpl extends BaseApiService implements MemberService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RegisterEmailProducter registerEmailProducter;

    @Value("${messages.queue}")
    private String MESSAGESQUEUE;

//    @Override
//    public Map<String, Object> testRest() {
//        Map<String, Object> result = new HashMap<>();
//        result.put("errorCode", "200");
//        result.put("errorMsg", "success");
//        baseRedisService.setString("xywmy","aaa",null);
//
//        log.info((String) baseRedisService.getString("xywmy"));
//        return result;
//
//    }

    @Override
    public ResponseBase findUserById(Long userId) {
        UserEntity userEntity = userDao.findByID(userId);
        if(userEntity==null){
            return setResultError("为查找到该用户信息");
        }
        return setResultSuccess(userEntity);

    }

    @Override
    public ResponseBase register(@RequestBody UserEntity user) {
        //验证参数
        if(user!=null){
            if(StringUtils.isNullOrEmpty(user.getUsername())){
                return setResultError("注册的用户账号不能为空");
            }
            if(StringUtils.isNullOrEmpty(user.getPassword())){
                return setResultError("注册的用户密码不能为空");
            }
        }else{
            return setResultError("注册的用户对象不能为空");
        }
        //注册到数据库
        String newPassWord = MD5Util.MD5(user.getPassword());
        user.setPassword(newPassWord);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        int insertCount = userDao.insertUser(user);
        if(insertCount<1){
            return setResultError("注册的用户失败");
        }
        //发邮件
        String emailJson = setMessege(user.getEmail());
        log.info("######email:{},messAageJson:{}",user.getEmail(),emailJson);
        sendMsg(emailJson);
        return setResultSuccess();
    }

    @Override
    public ResponseBase login(@RequestBody UserEntity userEntity) {
        //验证参数
        if(userEntity==null){
            return setResultError("登录用户参数不能为空");
        }else{
            if(StringUtils.isNullOrEmpty(userEntity.getUsername())){
                return setResultError("登录用户名不能为空");
            }
            if(StringUtils.isNullOrEmpty(userEntity.getPassword())){
                return setResultError("登录密码不能为空");
            }
        }
        //验证密码
        String password = userEntity.getPassword();
        String newPassword = MD5Util.MD5(password);
        UserEntity user = userDao.login(userEntity.getUsername(),newPassword);
        if(user!=null){
            return setLogin(user);
        }else{
            return setResultError("账号密码错误");
        }
    }

    @Override
    public ResponseBase findUserByToken(String token) {
        //获得用户id
        String userId = (String) baseRedisService.getString(token);
        if(StringUtils.isNullOrEmpty(userId)){
            return setResultError("token已经过期");
        }
        //获得用户
        UserEntity userEntity = userDao.findByID(new Long(userId));
        //有就返回用户登录成功
        if(userEntity!=null){
            return setResultSuccess(userEntity);
        }else{
            return setResultError("token已经过期");
        }
    }

    public ResponseBase setLogin(UserEntity userEntity) {
        String memberToken = TokenUtils.getMemberToken();
        //把token和userId保存到 redis  有效期90天
        log.info("####用户信息token存放在redis中... key为:{},value", memberToken, userEntity.getId());
        baseRedisService.setString(memberToken, userEntity.getId() + "", Constants.TOKEN_MEMBER_TIME);
        //多存放一步cookie 这样不用浏览器带着token  可以用cookie带 这一步放controller调用吧
//        Cookie cookie = new Cookie("memberToken",memberToken);
//        cookie.setMaxAge(60*60*24*90);
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
//                .getRequestAttributes();
//        HttpServletResponse response =  requestAttributes.getResponse();
//        response.addCookie(cookie);
        // 5.直接返回token
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberToken", memberToken);
        return setResultSuccess(jsonObject);

    }

    private void sendMsg(String emailJson) {
        //队列发送
        ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGESQUEUE);
        registerEmailProducter.sendMsg(activeMQQueue,emailJson);
    }

    /**
     * 封装的邮件对象
     *
     * @param mail
     */
    public String setMessege(String mail) {
        JSONObject header = new JSONObject();
        header.put("interfaceType", Constants.MESSAGE_INTERFACE_TYPE_EMAIL);
        JSONObject jo = new JSONObject();
        jo.put("header",header);
        JSONObject content = new JSONObject();
        content.put("mail",mail);
        jo.put("content",content);
        return jo.toString();
    }

}
